// order-detail.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    orderId: null,
    orderInfo: {},
    allocations: [],
    reports: [],
    progressData: {}
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/order-detail/order-detail')) {
      return
    }

    if (options.id) {
      this.setData({ orderId: options.id })
      this.loadOrderDetail(options.id)
    }
  },

  // 加载订单详情
  loadOrderDetail(orderId) {
    api.getOrderDetail(orderId).then(res => {
      const orderInfo = res.data
      
      // 格式化时间
      orderInfo.createtime_text = this.formatTime(orderInfo.createtime)
      orderInfo.delivery_date = this.formatDate(orderInfo.delivery_date)
      
      this.setData({ orderInfo })
      
      // 加载分工分配信息
      this.loadAllocations(orderId)
    }).catch(err => {
      console.error('加载订单详情失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    })
  },

  // 加载分工分配信息
  loadAllocations(orderId) {
    api.getAllocations({ order_id: orderId }).then(res => {
      const allocations = res.data.list || []
      
      // 只保留当前订单的分工分配
      const currentOrderAllocations = allocations.filter(item => item.order_id == orderId)
      
      // 格式化时间
      currentOrderAllocations.forEach(item => {
        item.createtime_text = this.formatTime(item.createtime)
        // 计算进度
        item.progress = item.quantity > 0 ? Math.round((item.reported_quantity / item.quantity) * 100) : 0
      })
      
      this.setData({ allocations: currentOrderAllocations })
      
      // 加载报工信息
      this.loadReports(orderId)
      
      // 计算生产进度
      this.calculateProgress(currentOrderAllocations)
    }).catch(err => {
      console.error('加载分工分配失败:', err)
    })
  },

  // 加载报工信息
  loadReports(orderId) {
    api.getReports({ order_id: orderId }).then(res => {
      const reports = res.data.list || []
      
      // 只保留当前订单的报工记录
      const currentOrderReports = reports.filter(item => item.allocation && item.allocation.order_id == orderId)
      
      // 格式化时间
      currentOrderReports.forEach(item => {
        item.createtime_text = this.formatTime(item.createtime)
        item.audit_time_text = item.audit_time ? this.formatTime(item.audit_time) : ''
      })
      
      this.setData({ reports: currentOrderReports })
    }).catch(err => {
      console.error('加载报工信息失败:', err)
    })
  },

  // 计算生产进度
  calculateProgress(allocations) {
    const progressData = {
      totalAllocated: 0,
      totalReported: 0,
      overallProgress: 0,
      productProgress: {}, // 按产品统计进度
      modelProgress: {}, // 按型号统计进度
      processProgress: {} // 按工序统计进度
    }
    
    // 获取订单的产品型号信息
    const orderModels = this.data.orderInfo.order_models || []
    
    // 初始化产品进度数据
    orderModels.forEach(orderModel => {
      const productKey = `${orderModel.model.product.name}-${orderModel.model.name}`
      progressData.productProgress[productKey] = {
        productName: orderModel.model.product.name,
        modelName: orderModel.model.name,
        totalQuantity: orderModel.quantity, // 订单中的总数量
        allocatedQuantity: 0, // 已分配数量
        reportedQuantity: 0, // 已报工数量
        progress: 0,
        processes: {} // 各工序的进度
      }
    })
    
    // 统计分工分配数据
    allocations.forEach(item => {
      progressData.totalAllocated += item.quantity
      progressData.totalReported += item.reported_quantity
      
      const productKey = `${item.model.product.name}-${item.model.name}`
      const processKey = item.process.name
      
      // 更新产品进度
      if (progressData.productProgress[productKey]) {
        progressData.productProgress[productKey].allocatedQuantity += item.quantity
        progressData.productProgress[productKey].reportedQuantity += item.reported_quantity
        
        // 初始化工序进度
        if (!progressData.productProgress[productKey].processes[processKey]) {
          progressData.productProgress[productKey].processes[processKey] = {
            allocated: 0,
            reported: 0,
            progress: 0
          }
        }
        progressData.productProgress[productKey].processes[processKey].allocated += item.quantity
        progressData.productProgress[productKey].processes[processKey].reported += item.reported_quantity
      }
      
      // 按型号统计进度（兼容旧逻辑）
      if (!progressData.modelProgress[productKey]) {
        progressData.modelProgress[productKey] = {
          allocated: 0,
          reported: 0,
          progress: 0
        }
      }
      progressData.modelProgress[productKey].allocated += item.quantity
      progressData.modelProgress[productKey].reported += item.reported_quantity
      
      // 按工序统计进度（兼容旧逻辑）
      if (!progressData.processProgress[processKey]) {
        progressData.processProgress[processKey] = {
          allocated: 0,
          reported: 0,
          progress: 0
        }
      }
      progressData.processProgress[processKey].allocated += item.quantity
      progressData.processProgress[processKey].reported += item.reported_quantity
    })
    
    // 计算各产品的进度
    Object.keys(progressData.productProgress).forEach(productKey => {
      const product = progressData.productProgress[productKey]
      
      // 计算各工序的进度
      Object.keys(product.processes).forEach(processKey => {
        const process = product.processes[processKey]
        process.progress = process.allocated > 0 ? Math.round((process.reported / process.allocated) * 100) : 0
      })
      
      // 计算产品的总体进度（按报工数量计算）
      product.progress = product.totalQuantity > 0 ? 
        Math.round((product.reportedQuantity / product.totalQuantity) * 100) : 0
    })
    
    // 计算总体进度（基于所有产品的总数量和总报工数量）
    const productKeys = Object.keys(progressData.productProgress)
    let totalOrderQuantity = 0
    let totalReportedQuantity = 0
    
    productKeys.forEach(key => {
      const product = progressData.productProgress[key]
      totalOrderQuantity += product.totalQuantity
      totalReportedQuantity += product.reportedQuantity
    })
    
    progressData.overallProgress = totalOrderQuantity > 0 ? 
      Math.round((totalReportedQuantity / totalOrderQuantity) * 100) : 0
    
    // 计算各型号进度（兼容旧逻辑）
    Object.keys(progressData.modelProgress).forEach(key => {
      const model = progressData.modelProgress[key]
      model.progress = model.allocated > 0 ? Math.round((model.reported / model.allocated) * 100) : 0
    })
    
    // 计算各工序进度（兼容旧逻辑）
    Object.keys(progressData.processProgress).forEach(key => {
      const process = progressData.processProgress[key]
      process.progress = process.allocated > 0 ? Math.round((process.reported / process.allocated) * 100) : 0
    })
    
    this.setData({ progressData })
  },

  // 编辑订单
  editOrder() {
    // 检查编辑权限
    if (!this.hasPermission('order_manage', 'edit')) {
      this.showPermissionDenied('order_manage', 'edit')
      return
    }

    wx.navigateTo({
      url: `/pages/create-order/create-order?id=${this.data.orderId}`
    })
  },

  // 返回列表
  goBack() {
    wx.navigateBack()
  },

  // 权限检查方法
  hasPermission(module, action) {
    const app = getApp()
    const adminInfo = app.globalData.adminInfo
    if (!adminInfo || !adminInfo.id) {
      return false
    }
    return permissionUtils.hasPermission(adminInfo.id, module, action)
  },

  // 显示权限不足提示
  showPermissionDenied(module, action) {
    const description = permissionUtils.getPermissionDescription(module, action)
    wx.showModal({
      title: '权限不足',
      content: `您没有${description}的权限`,
      showCancel: false,
      success: () => {
        wx.navigateBack()
      }
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 格式化日期
  formatDate(dateStr) {
    if (!dateStr) return '未设置'
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  }
}) 